package com.lzx.adx.report.controller.v1.vivo;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.lzs.adx.commmon.utils.JsonUtils;
import com.lzs.adx.commmon.utils.Result;
import com.lzx.adx.report.bean.mapper.ReportMapper;
import com.lzx.adx.report.cache.AccountLocalCache;
import com.lzx.adx.report.dto.AccountDTO;
import com.lzx.adx.report.dto.ReportDTO;
import com.lzx.adx.report.dto.ViVoData;
import com.lzx.adx.report.enums.ViVoTaoBaoCovertEnum;
import com.lzx.adx.report.model.vivo.ViVoRequest;
import com.lzx.adx.report.service.ReportService;
import com.lzx.adx.report.util.UrlUtil;
import com.lzx.adx.report.util.helper.TouTiaoHelper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RequestMapping("/vivo/yy")
@RestController
@Slf4j
public class VivoYyController {


    @Autowired
    private ReportService reportService;

    @Autowired
    private ThreadPoolTaskExecutor reportExecutor;

    @Autowired
    private ReportMapper reportMapper;



    @GetMapping("/report")
    public ResponseEntity report(ViVoRequest viVoRequest, HttpServletRequest request) {
        log.info("接收到vivo到优优的请求参数为{}", JsonUtils.toJsonString(viVoRequest));
        //1.收到监测的数据存储
        ReportDTO reportDTO = reportMapper.toReportDTO(viVoRequest);
        reportDTO.setBizRequestId(IdUtil.fastSimpleUUID()+reportDTO.getDspId());
        reportDTO.setCreateTime(new Date());
        reportDTO.setUpdateTime(new Date());
        reportDTO.setExtend(JsonUtils.toJsonString(viVoRequest));
        reportDTO.setTraceTime(String.valueOf(System.currentTimeMillis() / 1000));
        reportExecutor.execute(() -> {
            reportService.saveData(reportDTO);
        });
        reportDTO.setImei(null);
        reportDTO.setImeiSum(viVoRequest.getImei());
        reportDTO.setOaidSum(viVoRequest.getOaidMd5());
        AccountDTO accountDTO = AccountLocalCache.getInstance().get(viVoRequest.getDspId());
        String resultUrl = UrlUtil.covertYouYouUrl(accountDTO, reportDTO);
        log.info("账号{}vivo到优优请求完整的url为{}", viVoRequest.getDspId(), resultUrl);
        String result = HttpUtil.get(resultUrl);
        log.info("账号{}vivo到优优响应结果为{}", viVoRequest.getDspId(), result);
        return ResponseEntity.ok(new Result());
    }


    @GetMapping("/callback")
    public ResponseEntity<?> callback(String requestId, String transformType) {
        log.info("vivo接收了优优-天猫拉活回调信息请求流水号{},回调类型为{}", requestId, transformType);
        if (StringUtils.isBlank(requestId)||StringUtils.isBlank(transformType)) {
            log.info("vivo接收了优优-天猫拉活回调信息参数异常");
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
        }
        String event_time = String.valueOf(System.currentTimeMillis());
        //1.把转换结果更新到数据库
        Map<String, Object> params = new HashMap<>();
        params.put("bizRequestId", requestId);
        List<ReportDTO> list = reportService.list(params);
        ReportDTO reportDTO;
        if (CollectionUtil.isNotEmpty(list)) {
            reportDTO = list.get(0);
        } else {
            log.error("当前流水号，系统当前不存在");
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
        }
        //2.将结果上报给VIVO
        AccountDTO accountDTO = AccountLocalCache.getInstance().get(reportDTO.getDspId());
        String sspExtend = accountDTO.getSspExtend();
        JSONObject jsonObject = JSONObject.parseObject(sspExtend);
        String code = jsonObject.getString(transformType);
        if (StringUtils.isBlank(code)){
            log.info("vivo接收了优优-天猫拉活回调信息当前流水号：{}，事件类型{}不合法，不做数据回传", requestId,transformType);
            return ResponseEntity.ok(new Result());
        }
        reportDTO.setResultType(transformType);
        reportDTO.setResultTime(event_time);
        reportDTO.setUpdateTime(new Date());
        reportService.updateData(reportDTO,transformType);
        ViVoRequest viVoRequest = JSONObject.parseObject(reportDTO.getExtend(), ViVoRequest.class);
        ViVoData viVoData = new ViVoData();
        viVoData.setCvTime(event_time);
        viVoData.setCvType(code);
        viVoData.setRequestId(viVoRequest.getRequestId());
        viVoData.setCreativeId(viVoRequest.getContentId());
        if ("PAY".equals(code)){
            ViVoData.ExtParam extParam=new ViVoData.ExtParam();
            viVoData.setExtParam(extParam);
        }
        Map<String, Object> paramsMap = new HashMap<>();
        paramsMap.put("srcType","WEB");
        paramsMap.put("pageUrl",jsonObject.getString("pageUrl"));
        paramsMap.put("srcId",jsonObject.getString("srcId"));
        paramsMap.put("dataList",Lists.newArrayList(viVoData));
        String resultPams = JSON.toJSONString(paramsMap);
        String url = accountDTO.getSspApiUrl() + "?access_token=" + accountDTO.getSspKey() + "&timestamp=" + event_time + "&nonce=" + IdUtil.fastSimpleUUID() + "&advertiser_id=" + viVoRequest.getAccountId();
        log.info("账号{}，请求id{}优优-天猫拉活给vivo请求地址为地址为：{}，请求参数为{}", reportDTO.getDspId(), requestId, url, resultPams);
        String post = HttpUtil.post(url, resultPams);
        log.info("账号{}，请求id{}优优-天猫拉活给vivo请求转换响应的结果为：{}", reportDTO.getDspId(), requestId, post);
        return ResponseEntity.ok(new Result());
    }


}
